#!/usr/bin/env bash

cat <<EOF > /usr/local/bin/mongo-add-user.sh
#!/usr/bin/env bash
root_pwd=$1
database=$2
user=$3
password=$3

if [ -z "$database" ]; then
    echo "docker exec mongo mongo-add-user.sh root密码 数据库 新用户名 新密码"
    exit 1
fi

echo -e 'use '$database' \n db.createUser({ user: "'$user'", pwd:"'$password'", roles: [ {role:"'readWrite'",db:"'$database'"}]})'  \
|  mongo 127.0.0.1/admin -u root -p $root_pwd
EOF

chmod +x /usr/local/bin/mongo-add-user.sh

#---
cat <<EOF > /usr/local/bin/mongo-export.sh
#!/usr/bin/env bash
database=$1
user=$2
password=$3
path=$4


if [ -z "$database" ] || [ -z "$user" ] || [ -z "$password" ]; then
    echo "docker exec mongo mongo-export.sh 数据库 用户名 密码 备份目录(/data/mongo/\$database), 导出数据，每个表一个json文件"
    exit 1
fi

time=$(date "+%Y%m%d-%H%M")
if [ -z "$path" ]; then
    path="/data/mongo/$database/$time"
fi

echo "target path: $path"
mkdir -p $path

mongo --quiet $database -u $user -p $password --eval "db.getCollectionNames()" \
  | xargs \
  | awk '{print substr($0,2,length()-2)}' \
  | { read c; ary=(${c//,/});  for i in ${ary[@]};  do echo $i;  done  ; } \
  | { readarray ary ; for i in ${ary[@]};  do echo "mongoexport -d $database -u $user -p $password --collection $i  -o $path/$i.json && echo '['$i' done！]'";  done  ; } \
  | bash
EOF

chmod +x /usr/local/bin/mongo-export.sh

#---
cat <<EOF > /usr/local/bin/mongo-import.sh
#!/usr/bin/env bash
database=$1
user=$2
password=$3
path=$4
filter=$5

if [ -z "$database" ] || [ -z "$user" ] || [ -z "$password" ]; then
    echo "docker exec mongo mongo-import.sh 数据库 用户名 密码 备份目录(/data/mongo/\$database), 导入数据"
    exit 1
fi

time=$(date "+%Y%m%d-%H%M")
if [ -z "$path" ]; then
    path="/data/mongo/$database"
fi

if [ -z "$filter" ]; then
    filter=".json"
fi

echo "source path: $path"
echo "filter: $filter"

ls -l $path | grep ^[^d]  | grep $filter | awk '{print $9}' | awk '{print substr($0,0,length()-4)}' \
  | { readarray ary ; for i in ${ary[@]};  do echo "mongoimport -d $database -u $user -p $password --collection $i --file $path/$i.json && echo '['$i' done！]'";  done  ; } \
  | bash

EOF

chmod +x /usr/local/bin/mongo-import.sh


